const http = require("http");

const server = http.createServer(function (req, res) {
  console.log("Req: " + req.url);
  res.setHeader("Access-Control-Allow-Origin", "*");
  if (req.url !== "/query")
    res.setHeader("content-type", "text/html;charset=utf8");
  let delay = parseInt(Math.random() * 3000);
  switch (req.url) {
    case "/":
      res.end("Server Running!");
      break;
    case "/api1":
      setTimeout(() => res.end("api1:" + new Date()), delay);
      break;
    case "/api2":
      setTimeout(() => res.end("api2:" + new Date()), delay);
      break;
    case "/api3":
      setTimeout(() => res.end("api3:" + new Date()), delay);
      break;
    case "/api4":
      setTimeout(() => res.end("api4:" + new Date()), delay);
      break;
    case "/api5":
      setTimeout(() => res.end("api5:" + new Date()), delay);
      break;
    case "/api6":
      setTimeout(() => res.end("api6:" + new Date()), delay);
      break;
    case "/api7":
      setTimeout(() => res.end("api7:" + new Date()), delay);
      break;
    case "/api8":
      setTimeout(() => res.end("api8:" + new Date()), delay);
      break;
    default:
      if (req.url.startsWith("/query")) {
        let query={};
        let indexOf=req.url.indexOf('?');
        if(indexOf>0){
          let queryString=req.url.substring(indexOf+1);
          let splits=queryString.split('&');
          for(let i=0;i<splits.length;i++){
            indexOf=splits[i].indexOf('=');
            if(indexOf>0){
              let key=splits[i].substring(0,indexOf);
              let value=splits[i].substring(indexOf+1);
              query[key]=value;
            }
          }
        }
        let data=[];
        let len=parseInt(Math.random()*10);
        for(let i=0;i<len;i++)
          data.push(query.q+":"+i);
        setTimeout(() => {
          res.setHeader("content-type", "application/json;charset=utf8");
          res.end(
            JSON.stringify({
              code: 0,
              data: data,
            })
          );
        }, delay/3);
      } else res.end();
      break;
  }
});
// 3. 启动服务
server.listen(8081, function () {
  console.log("Http Server Started!");
});
